<template>
  <div class="gamecurrencydiff-list">
    <Row type="flex" justify="space-between" class="gamecurrencydiff-listt-edit">
      <Form style="width: 100%" class="from" label-position="left" inline>
        <Row type="flex" justify="space-between" inline>
          <!-- <Col  :xl="6"> -->
            <Row type="flex" justify="start" inline>

                <FormItem>
                  <RadioGroup @on-change="search" v-model="menu" type="button">
                    <Radio v-for="(item, index) in radioOption" :key="index" :label="item.key">
                      <span>{{item.value}}</span>
                    </Radio>
                  </RadioGroup>
                </FormItem>

            </Row>
          <!-- </Col> -->
          <!-- <Col  :xl="18"> -->
          <Row type="flex" justify="end" inline>

                        <FormItem :label-width="48">
              <div slot="label" style="transform: translateX(12px);">时间：</div>
              <datePickerYmd
                @on-change="search"
                :dataType="dataType"
                :dateOption="dateOption"
                :selectDateType.sync="selectDateType "
                v-model="timeDate"
              ></datePickerYmd>
            </FormItem>

            <FormItem :label-width="72">
              <div slot="label" style="transform: translateX(12px);">门店名称：</div>
              <vueTreeselectChoice
                :multiple="true"
                ref="vueTreeselectChoice"
                @input="handleShop"
                permissionCode="moms:report:coindiffanalytics"
                v-model="ShopValue"
                @on-api-finish="apiFinish"
              ></vueTreeselectChoice>
            </FormItem>

            <FormItem>
              <Button type="primary" class="coinrevenue-btn" @click="search">查询</Button>
            </FormItem>

            <FormItem v-if="hasPermission('moms:report:coindiffanalyticsexport')" >
              <Dropdown  @on-click="exportExcl" style="margin-left: 20px;">
                <Button type="primary">
                  导出
                  <Icon type="ios-arrow-down"></Icon>
                </Button>
                <DropdownMenu slot="list">
                  <DropdownItem
                    style="min-width: 140px;"
                    v-for="(item, index) in dropdownOptions"
                    :name="item.key"
                    :key="index"
                  >{{item.value}}</DropdownItem>
                </DropdownMenu>
              </Dropdown>
            </FormItem>

          </Row>

          <!-- </Col> -->
        </Row>
      </Form>
    </Row>
    <!-- :loading="isloading" -->
    <Table :max-height=" resData.length > 10 ? 538 : 0" :loading="isloading" border stripe :columns="columns" :data="resData"></Table>
    <div class="page-box" style="margin-top: 20px">
      <Page
        :total="page[`${menu}Total`]"
        :current.sync="page[`${menu}PageIndex`]"
        :page-size="page[`${menu}Limit`]"
        @on-change="handlePage"
        @on-page-size-change="handlePageSize"
        show-sizer
        :page-size-opts="$pageSizeOpts"
        show-total
      />
    </div>
    <div>
      <div style="padding-left: 20px; font-size: 13px;">
        <p v-for="(item, index) in tips" :key="index"> {{item}} </p>
        <!-- <p> 2.期初存币数(枚):统计当期在前台、一体机电子取币数(枚) </p>
        <p> 3.期初存币数(枚):统计当期在前台、一体机电子取币数(枚) </p>
        <p> 4.期初存币数(枚):统计当期在前台、一体机电子取币数(枚) </p>
        <p> 4.期初存币数(枚):统计当期在前台、一体机电子取币数(枚) </p> -->
      </div>
    </div>
    <down-center ref="downCenterRef"
                 perms="moms:report:coindiffanalytics"
                 v-if="hasPermission('moms:report:coindiffanalyticsexport')"></down-center>
  </div>
</template>
<script>
import dayjs from 'dayjs'
import errorCaptured from '@/libs/errorCaptured'
// import { formatAmount } from '@/libs/tools'
// 需求文档14、明细显示：按月查看，列表中增加“操作”字段，可点击查询明细；明细表增加时间字段，可显示查询当期全部流转明细
import {
  // coinDeviceExport,
  // coinDeviceDetailExport,
  coinDeviceDaily,
  coinSaleDaily,
  // coinSaleExport,
  // coinSaleDetailExport,
  coinMemberDily
  // coinMemberDetailExport,
  // coinMemberDilyExport
} from '@/api/report/finance'
import datePickerYmd from '@/components/date-picker-ymd/date-picker-ymd.vue'
import vueTreeselectChoice from '@/components/vue-treeselect-choice'
// import { blobToXls } from '@/libs/blobToXls'
import DownCenter from '@/view/components/down-center/index.vue'
export default {
  name: 'report_finance_gamecurrencydiff',
  components: {
    datePickerYmd,
    vueTreeselectChoice,
    DownCenter
    // vueTreeselectShop
  },
  data () {
    return {
      ShopValue: [],
      radioOption: [
        { key: 'member', value: '会员资产' },
        { key: 'device', value: '硬件设备' },
        { key: 'sales', value: '销售核对' }
      ],
      DropdownItem: [
        { key: 'member', value: '会员资产汇总表' },
        { key: 'memberDetail', value: '会员资产明细表' },
        { key: 'device', value: '硬件设备汇总表' },
        { key: 'deviceDetail', value: '硬件设备明细表' },
        { key: 'sales', value: '销售核对汇总表' },
        { key: 'salesDetail', value: '销售核对明细表' }
      ],
      menu: 'member',
      isloading: false,
      timeDate: [
        dayjs()
          .subtract(1, 'day')
          .format('YYYY-MM-DD 00:00:00'),
        dayjs()
          .subtract(1, 'day')
          .format('YYYY-MM-DD 00:00:00')
      ],
      selectDateType: 'date',
      dataType: [{ key: 'date', value: '日' }, { key: 'month', value: '月' }],
      dateOption: {
        disabledDate: date => {
          return dayjs(date).isAfter(dayjs(new Date()).subtract(1, 'day'))
        }
      },
      page: {
        memberOffset: 0,
        memberLimit: 10,
        memberPageIndex: 1,
        memberTotal: 0,

        deviceOffset: 0,
        deviceLimit: 10,
        devicePageIndex: 1,
        deviceTotal: 0,

        salesOffset: 0,
        salesLimit: 10,
        salesPageIndex: 1,
        salesTotal: 0
      },
      searchObj: {
        shopIds: [],
        merchantId: this.$store.state.user.merchantId
      },

      memberColumns: [
        { title: '门店', key: 'shopName', align: 'center' },
        { title: '期初存币数(枚)', key: 'lastDepositNum', align: 'center' },
        { title: '售赠币数(枚)', key: 'coinGiftNum', align: 'center' },
        { title: '期末存币数(枚)', key: 'depositNum', align: 'center' },
        { title: '机台回收币数(枚)', key: 'machineReceiveNum', align: 'center' },
        { title: '偏差数(枚)', key: 'deviation', align: 'center' }
      ],
      deviceColumns: [
        { title: '门店', key: 'shopName', align: 'center' },
        { title: '电子取币数(枚)', key: 'withdrawEcoinNum', align: 'center' },
        { title: '实体取币数(枚)', key: 'withdrawCoinNum', align: 'center' },
        { title: '电子退币数(枚)', key: 'outEcoinNum', align: 'center' },
        { title: '实体退币数(枚)', key: 'outCoinNum', align: 'center' },
        { title: '机台回收数(枚)', key: 'machineReceiveNum', align: 'center' },
        { title: '偏差数(枚)', key: 'deviation', align: 'center' }
      ],
      salesColumns: [
        { title: '门店', key: 'shopName', align: 'center' },
        { title: '期末结存数(枚)', key: 'depositNum', align: 'center' },
        { title: '期末存币总数(枚)', key: 'depositSumNum', align: 'center' },
        { title: '偏差数(枚)', key: 'diffNum', align: 'center' }
      ],
      salesData: [],
      memberData: [],
      deviceData: []
    }
  },
  computed: {
    resData () {
      // return [{ shopName: 11 }, { shopName: 11 }]
      return this[`${this.menu}Data`]
    },
    startDate () {
      return this.timeDate[0]
    },
    tips () {
      let obj = {}
      obj.member = [
        '1、期初存币数(枚):统计上期期末此门店所有会员可用游戏币数量(枚)',
        '2、售赠币数(枚):取值当期游戏币售赠总数(枚)',
        '3、期末存币数(枚):统计当期此门店所有会员可用游戏币数量(枚)',
        '4、机台收回币数(枚):取值当期所有机台回收币数(枚)',
        '5、偏差:期初存币数(枚) + 售赠币数(枚) - 期末存币数(枚) - 机台收回币数(枚)'
      ]
      obj.device = [
        '1、电子取币数(枚):统计当期在前台、一体机电子取币数(枚)',
        '2、实体取币数(枚):统计当期在前台、一体机取实体币数(枚)',
        '3、电子退币数(枚):统计当期在前台、一体机退电子游戏币币数(枚)',
        '4、实体退币数(枚):统计当期在前台、一体机和存币机退实体游戏币币数(枚)',
        '5、机台回收数(枚):取值当期所有机台吸收币数总数(枚)',
        '6、偏差数:电子取币数(枚) + 实体取币数(枚) - 电子退币数(枚) - 实体退币数(枚) - 机台回收数(枚)'
      ]
      obj.sales = [
        '1、期末结存数(枚):统计当期此门店所有会员可用游戏币数量',
        '2、期末存币总数(枚):取值游戏币收入汇总表中的期末存币总数。(上期期末存币数 + 当期售赠币总数 - 当期机台吸币数)',
        '3、偏差:期末结存数(枚) - 期末存币总数(枚)'
      ]
      return obj[this.menu]
    },
    dropdownOptions () {
      if (this.selectDateType === 'date') return this.DropdownItem.filter(item => !item.key.includes('Detail'))
      return this.DropdownItem
    },
    columns () {
      this.setColumns()
      return this[`${this.menu}Columns`]
    },
    endDate () {
      if (this.selectDateType === 'daterange') {
        return dayjs(this.timeDate[1])
          .add(1, 'day')
          .format('YYYY-MM-DD 00:00:00')
      }
      return this.timeDate[1]
    }
  },

  async created () {
    // console.log(this)
    // console.log(this.$options.name)
    // window.addEventListener('resize', () => {
    //   console.log(document.body.clientWidth )
    // },false)
  },
  mounted () {},
  methods: {
    apiFinish (isId) {
      // if (isId) this.ShopValue = [this.$store.state.user.orgId]
      // this.ShopValue = []
    },
    setColumns () {
      let obj = {
        title: '查看详情',
        key: 'action',
        align: 'center',
        render: (h, params) => {
          if (params.row.status === 0) return null
          return h('div', [
            h('i', {
              class: ['iconsys', 'icondetail'],
              on: {
                click: () => {
                  this.$router.push({
                    name: 'report_finance_gamecurrencydiff_detail',
                    params: {
                      // :id/:startTime/:endTime/:menu
                      id: params.row.shopId,
                      startTime: this.startDate,
                      endTime: this.endDate,
                      menu: this.menu,
                      shopName: params.row.shopName,
                      dateType: this.selectDateType
                    }
                  })
                  // console.log(2323)
                  // this.errorsList = params.row.errors
                  // this.modalMachineShow = true
                }
              }
            })
          ])
        }
      }
      if (this.selectDateType === 'date') {
        if (this[`${this.menu}Columns`][this[`${this.menu}Columns`].length - 1]['key'] === 'action') {
          this[`${this.menu}Columns`].pop()
        }
      } else {
        if (this[`${this.menu}Columns`][this[`${this.menu}Columns`].length - 1]['key'] !== 'action') {
          this[`${this.menu}Columns`].push(obj)
        }
      }
    },
    handlePage (val) {
      this.page[`${this.menu}Offset`] = (val - 1) * this.page[`${this.menu}Limit`]
      this.getLIst()
      // this.searchObj.offset = (val - 1) * this.searchObj.limit
    },
    handlePageSize (val) {
      this.page[`${this.menu}Limit`] = val
      // this.page[`${this.menu}Offset`] = 0
      this.search()
    },
    async getLIst () {
      const obj = {
        member: coinMemberDily,
        device: coinDeviceDaily,
        sales: coinSaleDaily
      }
      let params = {
        ...this.searchObj,
        offset: this.page[`${this.menu}Offset`],
        limit: this.page[`${this.menu}Limit`],
        startDate: this.startDate,
        endDate: this.endDate
      }
      // let testParams = {
      //   merchantId: '40ed3fb4-6b8a-4606-9cb3-a1e8bba5584b',
      //   shopIds: [
      //     'aaae3be8-0323-4208-b903-638d4d8949c5',
      //     '25e9e192-ba44-4e76-b633-4f044d8fb2a0',
      //     '279a26f2-8580-4e3e-b674-0702ce6322c9',
      //     '2bd82e13-3cad-47fe-978c-cdc291bf623b',
      //     '2e1a20de-ba95-4766-9826-d5d7a9413b36',
      //     '2fe3b7ef-18bc-4174-9960-72a9e4df27a0',
      //     '32033023-e0d1-44e6-9995-b7b5882f0816',
      //     '34818a39-9dd0-4529-9b26-89924e0cd008',
      //     '34c08b48-197a-4c87-958b-1225695e65e4',
      //     '35f0863e-166f-4423-bf93-6b8148a869a8',
      //     '37e92146-a32e-416c-814b-b8640e9890cc',
      //     '3c91895d-99da-4212-960b-970767aba393'
      //   ],
      //   startDate: '2019-08-10 00:00:00',
      //   endDate: '2019-08-11 00:00:00',
      //   offset: this.page[`${this.menu}Offset`],
      //   limit: this.page[`${this.menu}Limit`]
      // }
      const [err, res] = await errorCaptured(obj[this.menu], params)
      if (err) return null
      if (res.data.status !== 200) return this.$Message.error(`${res.data.error}`)
      // console.log(this[`${this.menu}Data`])
      // debugger
      this[`${this.menu}Data`] = res.data.data || []
      this.page[`${this.menu}Total`] = res.data.totalCount || 0
    },
    async search () {
      if (!this.searchObj.shopIds.length) return this.$Message.error('请选择门店')
      this.page[`${this.menu}Offset`] = 0
      this.page[`${this.menu}PageIndex`] = 1
      this.getLIst()

      // const pai = {
      //   member: 'member',
      //   device: 'device',
      //   sales: 'sales'
      // }
    },
    // 店铺改变
    async handleShop () {
      const ids = await this.$refs.vueTreeselectChoice.getShopId()
      this.searchObj.shopIds = ids
      this.search()
    },
    async exportExcl (key) {
      if (!this.searchObj.shopIds.length) return this.$Message.error('请选择门店')
      const name = {
        member: 'statShopAssetDaily',
        memberDetail: 'statShopAssetDetailDaily',
        device: 'statDeviceCoinMonth',
        deviceDetail: 'statDeviceCoinDaily',
        sales: 'statShopSalesDaily',
        salesDetail: 'statShopSalesDetailDaily'
      }
      this.$refs.downCenterRef.addTask({
        merchantId: this.$store.state.user.merchantId,
        shopIds: this.searchObj.shopIds,
        startDate: this.startDate,
        endDate: this.endDate,
        dateType: { year: 2, month: 1, date: 0 }[this.selectDateType],
        taskModule: name[key]
      })
      // const obj = {
      //   member: coinMemberDilyExport,
      //   memberDetail: coinMemberDetailExport,
      //   device: this.selectDateType === 'month' ? coinDeviceExport : coinDeviceDetailExport,
      //   deviceDetail: coinDeviceDetailExport,
      //   sales: coinSaleExport,
      //   salesDetail: coinSaleDetailExport
      // }

      // const name = {
      //   member: '会员资产游戏币流转差异汇总表',
      //   memberDetail: '会员资产游戏币流转差异明细表',
      //   device: '硬件设备游戏币流转差异表汇总表',
      //   deviceDetail: '硬件设备游戏币流转差异明细表',
      //   sales: '销售核对游戏币流转差异汇总表',
      //   salesDetail: '销售核对游戏币流转差异明细表'
      // }
      // let time = null
      // if (this.selectDateType === 'date') {
      //   time = dayjs(this.startDate).format('YYYY-MM-DD')
      // } else if (this.selectDateType === 'month') {
      //   time = dayjs(this.startDate).format('YYYY-MM')
      // } else if (this.selectDateType === 'year') {
      //   time = dayjs(this.startDate).format('YYYY')
      // }
      // let params = {
      //   ...this.searchObj,
      //   startDate: this.startDate,
      //   endDate: this.endDate
      // }
      // const [err, res] = await errorCaptured(obj[key], params)
      // if (err) return null
      // blobToXls(res.data, `${name[key]}(${time})`)
    }
  }
}
</script>
<style lang="less" scoped>
.gamecurrencydiff-list {
  // min-width: 1126px;
  // overflow: auto;

  // .from {
  //   margin-top: 24px;
  // }
  .gamecurrencydiff-listt-edit {
    padding-top: 20px;
    padding-left: 20px;
    padding-right: 20px;
    margin-bottom: -4px;
  }
  .button_active {
    border: 1px solid #2d8cf0;
  }
  .ivu-radio-group-button .ivu-radio-wrapper-checked {
    background: #2d8cf0;
    color: #fff;
  }
}
</style>
